package com.system.web.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class UploadServlet extends HttpServlet
{
  private static final long serialVersionUID = 1L;
  public static final Log logger = LogFactory.getLog(UploadServlet.class);

  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
  {
    try {
      DiskFileItemFactory factory = new DiskFileItemFactory();
      factory.setRepository(new File(getServletContext().getRealPath("/WEB-INF/temp")));
      ServletFileUpload upload = new ServletFileUpload(factory);
      String savepath = getServletContext().getRealPath("/WEB-INF/upload");

      upload.setHeaderEncoding("utf-8");

      upload.setFileSizeMax(10485760L);

      List<FileItem> list = upload.parseRequest(req);
      for (FileItem obj : list)
      {
        if (!"uuid".equals(obj.getFieldName()))
          continue;
        savepath = savepath + "/" + obj.getString();
        break;
      }

      for (FileItem item : list) {
        if (item.isFormField())
          continue;
        String exp = item.getName().substring(item.getName().lastIndexOf(".") + 1);
        if ((!"xls".equals(exp)) && (!"xlsx".equals(exp)))
          continue;
        InputStream in = item.getInputStream();
        int len = 0;
        byte[] buffer = new byte[1024];
        FileOutputStream out = new FileOutputStream(savepath);
        while ((len = in.read(buffer)) > 0) {
          out.write(buffer, 0, len);
        }
        in.close();
        out.close();
        item.delete();
      }

      resp.getWriter().print("success");

      logger.info("文件上传成功");
    }
    catch (Exception e)
    {
      logger.error("文件上传失败\n" + e.getMessage());
    }
  }

  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
  {
    doGet(req, resp);
  }
}